package practice;


import java.util.TreeMap;

public class MapSum {

    private class Node{
        public TreeMap<Character, Node> next;
        public int value;   //

        public Node(int value){
            this.value = value;
            next = new TreeMap<>();
        }

        public Node(){
            this(0);
        }
    }

    private Node root;

    public MapSum(){
        root = new Node();
    }

    public void insert(String key , int val){
        Node cur = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if(cur.next.get(c) == null){
                //添加进Trie中
                cur.next.put(c,new Node());
            }
            cur = cur.next.get(c);
        }
        cur.value = val;

    }

    // 找到当前 Trie 中 以指定字符串
    public int sum(String prefix){

        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null){
                return 0;
            }
            cur = cur.next.get(c);
        }

        //遍历以cur为根节点的
        return sum(cur);

    }

    // 遍历Node的所有子树，将子树中，所有节点的值加起来
    private int sum(Node node){

        if(node.next.size() == 0){
            return node.value;
        }

        int result = node.value;
        for(char c: node.next.keySet()){
            int x = sum(node.next.get(c));
            result = result + x;
        }

        return result;
    }


}
